package handler

import (
	"net/http"

	restful "github.com/emicklei/go-restful"
)

type UserHandler struct{}
type User struct {
	Id, Name string
}

// CreateHTTPAPIHandler creates the restful Container and defines the routes the API will serve
func CreateUserServiceHandler() (http.Handler, error) {
	userHandler := UserHandler{}

	wsContainer := restful.NewContainer()

	wsContainer.EnableContentEncoding(true)

	cors := restful.CrossOriginResourceSharing{
		AllowedHeaders: []string{"Content-Type", "Accept"},
		AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
		CookiesAllowed: true,
		Container:      wsContainer,
	}
	wsContainer.Filter(cors.Filter)
	wsContainer.Filter(wsContainer.OPTIONSFilter)

	apiV1Ws := new(restful.WebService)

	apiV1Ws.Path("/users").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)

	apiV1Ws.Route(
		apiV1Ws.POST("").To(userHandler.updateUser))

	wsContainer.Add(apiV1Ws)
	return wsContainer, nil
}

func NewUserService() *restful.WebService {
	service := new(restful.WebService)
	service.
		Path("/users").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)

	service.Route(service.POST("").To(updateUser))

	return service
}

func updateUser(request *restful.Request, response *restful.Response) {
	usr := new(User)
	err := request.ReadEntity(&usr)
	// here you would update the user with some persistence system
	if err == nil {
		response.WriteEntity(usr)
	} else {
		response.WriteError(http.StatusInternalServerError, err)
	}
}

func (userHandler *UserHandler) updateUser(request *restful.Request, response *restful.Response) {
	usr := new(User)
	err := request.ReadEntity(&usr)
	// here you would update the user with some persistence system
	if err == nil {
		response.WriteEntity(usr)
	} else {
		response.WriteError(http.StatusInternalServerError, err)
	}
}
